"use client";
import { ServiceTypes } from "@/api/customservice";
import { getPaysApi, lredPacketApi, PayDataType, redPacketApi } from "@/api/promo";
import RedPacketModal, { RedPacketModalProps } from "@/components/Box/RedPacketModal";
import SlotsModal, { SlotModalRefProps } from "@/components/Box/SlotsModal";
import UserRecharge, { ModalRefProps, Timeout } from "@/components/Box/UserRecharge";
import WheelModal, { WheelModalProps } from "@/components/Box/WheelModal";

import { getWheelApi } from "@/api/cashWheel";
import { getGiveInfoApi } from "@/api/slots";
import { Link } from "@/i18n/routing";
import { useGlobalNoticeStore } from "@/stores/useGlobalNoticeStore";
import { useSocialStore } from "@/stores/useSocials";
import useWheelStore from "@/stores/useWheelStore";
import { getToken } from "@/utils/Cookies";
import { useRequest } from "ahooks";
import { Badge } from "antd-mobile";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { FC, useEffect, useRef } from "react";

interface Props {
    services: ServiceTypes[];
    socials: ServiceTypes[];
}

const ServiceWidget: FC<Props> = (props) => {
    const token = getToken();
    const { services, socials = [] } = props;

    const { wheelStatus, wheelCurrent, setWheel } = useWheelStore((state) => ({
        wheelStatus: state.status,
        wheelCurrent: state.currentWheel,
        setWheel: state.setWheel,
    }));
    const defaultService = services?.find((item) => item.is_suspend === 1);

    const newServices = services?.filter((item) => item.status === 1) || [];
    const setSocials = useSocialStore((state) => state.setSocials);
    const redPacketModalRef = useRef<RedPacketModalProps>(null);

    /// 首充活动ref
    const userRechargeRef = useRef<ModalRefProps | null>(null);

    // 轮盘
    const wheelModalRef = useRef<WheelModalProps | null>(null);

    const slotsRef = useRef<SlotModalRefProps | null>(null);

    const getWheel = () => {
        if (!getToken()) return Promise.resolve(undefined);
        return getWheelApi().then((res) => {
            return res.data;
        });
    };
    useEffect(() => {
        // 数据存储，侧边栏使用
        setSocials(socials);
        setWheel().then((data) => {
            if (data && useWheelStore.getState().status === 1) {
                wheelModalRef.current?.onOpen(data);
            }
        });
    }, []);

    const t = useTranslations("HomePage");
    const { unread, userUnred } = useGlobalNoticeStore((state) => ({
        unread: state.unread,
        userUnred: state.userUnred,
    }));

    const getRedPacketInfo = async () => {
        try {
            let redPacketInfo: any;
            let actList: any = [];
            if (token) {
                redPacketInfo = await lredPacketApi();
                actList = redPacketInfo.data?.red_packets || [];
            } else {
                redPacketInfo = await redPacketApi();
                actList = redPacketInfo.data || [];
            }

            // 是否有已开始但是没领过的红包
            return actList.filter((aItem: any) => {
                return aItem.can_receive && aItem.is_start && !aItem.is_receive;
            });
        } catch (error) {
            console.log("redPacketInfo===>error:", error);
        }
    };
    // 红包雨轮询
    const { data: packets, run } = useRequest<any[], any>(getRedPacketInfo, {
        pollingInterval: 5000,
        pollingErrorRetryCount: 1,
        pollingWhenHidden: false,
    });

    // 首充活动
    const getPayInfo = async (): Promise<PayDataType> => {
        if (token) {
            const result = await getPaysApi();
            return result.data;
        } else {
            return Promise.resolve({
                first_pay: [],
                pay: [],
            });
        }
    };
    const { data: paysInfo, run: payRun } = useRequest<PayDataType, any>(getPayInfo, {
        pollingErrorRetryCount: 1,
        pollingWhenHidden: false,
    });

    /**
     * 免费送活动
     */

    const getSlots = async () => {
        if (token) {
            const result = await getGiveInfoApi();
            return result.data;
        } else {
            return Promise.resolve({});
        }
    };

    const { data: slots, run: slotRun } = useRequest<any, any>(getSlots, {
        pollingErrorRetryCount: 1,
        pollingWhenHidden: false,
    });
    const slotHandler = () => {
        slotsRef.current?.onOpen(slots);
    };
    return (
        <>
            <div
                className={`absolute bottom-[0.84rem] right-[0.12rem] z-50 flex w-[0.6944rem] flex-col items-center justify-center`}
            >
                {slots?.id ? (
                    <img
                        src={"/slots/slots-icon.gif"}
                        className={"mb-[0.2778rem] w-[100%]"}
                        onClick={slotHandler}
                    />
                ) : null}

                {/*轮盘  */}
                {wheelStatus === 2 ? (
                    <Link
                        href={"/cashWheel"}
                        className={
                            "mb-[0.2778rem] flex h-[0.54rem] w-[0.54rem] items-center" +
                            " justify-center rounded-[50%] bg-gradient-to-b from-[#0575e6] to-[#00f260]"
                        }
                    >
                        <Image
                            src={"/wheels/wheel-icon.gif"}
                            alt={"wheel"}
                            width={100}
                            height={100}
                        />
                    </Link>
                ) : null}
                {/*首充*/}
                {paysInfo?.first_pay?.map((item, index) => {
                    return (
                        <div
                            key={index}
                            className={`mb-[0.2778rem] flex cursor-pointer flex-col items-center`}
                        >
                            <img
                                className={"w-[0.54rem]"}
                                src="/hby/recharge.png"
                                onClick={() => {
                                    // @ts-ignore
                                    userRechargeRef.current?.onOpen(paysInfo.first_pay, index);
                                }}
                            />
                            {item.end_time > 0 ? (
                                <Timeout
                                    className={
                                        "relative before:left-0 before:top-0 before:content-['']" +
                                        " -m-[0.0417rem] before:h-[100%] before:blur-[0.0486rem]" +
                                        " before:absolute before:-z-10 before:w-[100%] before:bg-[#ed9d00]" +
                                        " text-[0.08rem]" +
                                        " z-1 text-[#fff]"
                                    }
                                    endTime={item.end_time}
                                    onEndHandler={payRun}
                                />
                            ) : null}
                        </div>
                    );
                })}
                {/* 红包雨icon */}
                {packets?.map((item, index) => {
                    return (
                        <div key={index} className={`mb-[0.2778rem] cursor-pointer`}>
                            <img
                                className={"w-[0.54rem] object-fill"}
                                src="/hby/red-icon.gif"
                                onClick={() => {
                                    redPacketModalRef.current?.onOpen(packets, index);
                                }}
                            />
                        </div>
                    );
                })}

                {/*未读消息*/}
                {unread || userUnred ? (
                    <Link
                        href={"/notification"}
                        className={
                            "mb-[0.2778rem] flex h-[0.54rem] w-[0.54rem] items-center" +
                            " justify-center rounded-[50%] bg-gradient-to-t from-[#ffa111]" +
                            " to-[#ffcf35]"
                        }
                    >
                        <Badge content={userUnred + unread} style={{ "--top": "12px" }}>
                            <i
                                className={"iconfont icon-duanxinguanli text-[0.3rem] text-[#fff]"}
                            ></i>
                        </Badge>
                    </Link>
                ) : null}

                {defaultService && (
                    <Link
                        href={defaultService.url}
                        className={
                            "flex h-[0.54rem] w-[0.54rem] items-center justify-center rounded-[50%]" +
                            " bg-gradient-to-t from-[#ff611b] to-[#ffcf35]"
                        }
                        target={"_blank"}
                    >
                        <img
                            className={"h-[0.3889rem] w-[0.3889rem] object-contain"}
                            src={defaultService.icon_url}
                            alt={""}
                        ></img>
                    </Link>
                )}
            </div>

            {/*红包雨弹窗*/}
            <RedPacketModal ref={redPacketModalRef} onAfterHandler={run} />

            {/*首充弹窗*/}
            <UserRecharge ref={userRechargeRef} />

            {/*  轮盘弹窗 */}
            <WheelModal ref={wheelModalRef} />

            {/*随机送*/}
            <SlotsModal ref={slotsRef} onAfterHandler={slotRun} />

            <div
                className={`grid`}
                style={{
                    gridTemplateColumns: ` repeat(${newServices && newServices.length >= 5 ? 5 : (newServices?.length ?? 1)},1fr)`,
                }}
            >
                {newServices.map((service, index) => {
                    return (
                        <Link
                            key={index}
                            href={service.url}
                            target={"_blank"}
                            className="bg-white m-[0.05rem] h-[0.3889rem] w-[0.3889rem] rounded"
                        >
                            <img
                                className={"h-[0.3889rem] w-[0.3889rem]"}
                                src={service.icon_url}
                            ></img>
                        </Link>
                    );
                })}
            </div>

            <div className={"text-[#ff6a01]"}>{t("Service")}</div>

            {/*share*/}
            <div className={"my-[0.2rem] text-[0.08rem] text-[#adadad]"}>{t("Share")}</div>

            <div
                className={`grid`}
                style={{
                    gridTemplateColumns: ` repeat(${socials.length >= 5 ? 5 : socials.length},1fr)`,
                }}
            >
                {socials.map((service, index) => {
                    return (
                        <Link
                            key={index}
                            href={service.url}
                            target={"_blank"}
                            className="bg-white m-[0.05rem] h-[0.3889rem] w-[0.3889rem] rounded"
                        >
                            <img
                                className={"h-[0.3889rem] w-[0.3889rem]"}
                                src={service.icon_url}
                            ></img>
                        </Link>
                    );
                })}
            </div>
        </>
    );
};

export default ServiceWidget;
